/**
 * Created by admin on 4/20/16.
 */
forms.fields = (function ($) {
    var TextField, NumericField, IntegerField,
        DateTimeField, DateField, TimeField,
        EmailField, UrlField, CharField,
        Select,TreeSelect,
        make_input,make_datepicker

    make_input = function (label, name, placeHolder,value) {
        return function ($parent, options) {
            var configMap = {
                    defaults: {
                        label: label,
                        name: name + new Date().getTime(),
                        placeHolder: placeHolder,
                        value : value?value:''
                    }
                },
                jqueryMap = {},
                setJqueryMap, setLabel,getLabel,setValue, getValue, enable, disable, setName, getName, setPlaceHolder, getPlaceHolder

            setJqueryMap = function () {
                var
                    main_html = String() +
                        '<div class="form-group">' +
                        '<label class="col-md-3 control-label">' + configMap.defautls.label + '</label>' +
                        '<div class="col-md-9">' +
                        '<input type="text" class="form-control" placeholder="' + configMap.defautls.placeHolder + '" name="' + configMap.defautls.name + '" value="' + configMap.defautls.value + '">' +
                        '</div>' +
                        '</div>',
                    $container = $(main_html),
                    $label = $container.find("label"),
                    $input = $container.find("input")

                jqueryMap['$container'] = $container
                jqueryMap['$label'] = $label
                jqueryMap['$input'] = $input
            }

            getLabel = function(){
                return jqueryMap.$label.text()
            }

            setLabel = function(label){
                jqueryMap.$label.html(label)
            }

            setValue = function (value) {
                jqueryMap.$input.val(value)
            }

            getValue = function () {
                return jqueryMap.$input.val()
            }

            enable = function () {
                jqueryMap.$input.enable()
            }

            disable = function () {
                jqueryMap.$input.disable()
            }

            setName = function (name) {
                jqueryMap.$input.attr('name', name)
            }

            getName = function () {
                return jqueryMap.$input.attr('name')
            }

            setPlaceHolder = function (palaceHolder) {
                jqueryMap.$input.attr('placeholder', placeholder)
            }

            getPlaceHolder = function () {
                return jqueryMap.$input.attr('placeholder')
            }


            $.extend(configMap.defaults, options)
            setJqueryMap()
            $parent.append(jqueryMap.$container)

            return {
                getLabel : getLabel,
                setLabel : setLabel,
                getValue: getValue,
                setValue: setValue,
                getName: getName,
                setName: setName,
                getPlaceHolder: getPlaceHolder,
                setPlaceHolder: setPlaceHolder,
                enable: enalbe,
                disable: disable
            }
        }
    }

    make_datepicker = function (label, name, value, dateFormat) {
        return function ($parent, options) {
            var configMap = {
                    defaults: {
                        label: label,
                        name: name + new Date().getTime(),
                        dateFormat : dateFormat,
                        value : value?value:new Date().getDate().toString()
                    }
                },
                jqueryMap = {},
                setJqueryMap, setLabel,getLabel,setValue, getValue, enable, disable, setName, getName

            setJqueryMap = function () {
                var
                    main_html = String() +
                        '<div class="form-group">' +
                            '<label for="dtp_input1" class="col-md-3 control-label">'+ configMap.defaults.label +'</label>' +
                            '<div class="col-md-9">' +
                                '<div class="input-group date form_datetime col-md-12" data-date-format="'+ configMap.defaults.dateFormat +'">' +
                                    '<input class="form-control" type="text" value="'+ configMap.defaults.value +'" readonly name="'+ configMap.defaults.name + '">'+
                                    '<span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span>'+
                                    '<span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span>' +
                                '</div>'+
                            '</div>'+
                        '</div>'
                    $container = $(main_html),
                    $label = $container.find("label"),
                    $input = $container.find("input")

                jqueryMap['$container'] = $container
                jqueryMap['$label'] = $label
                jqueryMap['$input'] = $input

                $input.parent('div').datetimepicker({
                    language:  'zh-CN',
                    weekStart: 1,
                    autoclose: 1,
                    todayHighlight: 1,
                    startView: 2,
                    minView: 2,
                    forceParse: 0,
                    showMeridian: 1
                })
            }

            getLabel = function(){
                return jqueryMap.$label.text()
            }

            setLabel = function(label){
                jqueryMap.$label.html(label)
            }

            setValue = function (value) {
                jqueryMap.$input.val(value)
            }

            getValue = function () {
                return jqueryMap.$input.val()
            }

            enable = function () {
                jqueryMap.$input.enable()
            }

            disable = function () {
                jqueryMap.$input.disable()
            }

            setName = function (name) {
                jqueryMap.$input.attr('name', name)
            }

            getName = function () {
                return jqueryMap.$input.attr('name')
            }


            $.extend(configMap.defaults, options)
            setJqueryMap()
            $parent.append(jqueryMap.$container)

            return {
                getLabel : getLabel,
                setLabel : setLabel,
                getValue: getValue,
                setValue: setValue,
                getName: getName,
                setName: setName,
                enable: enalbe,
                disable: disable
            }
        }
    }

    CharField = make_input({
        label: 'CharField',
        name: 'CharField',
        placeHolder: '输入文本'
    })

    IntegerField = make_input({
        label: 'IntegerField',
        name: 'IntegerField',
        placeHolder: '输入整数'
    })

    NumericField = make_input({
        label: 'NumericField',
        name: 'NumericField',
        placeHolder: '输入数值'
    })

    EmailField = make_input({
        label: 'EmailField',
        name: 'EmailField',
        placeHolder: '输入邮箱地址'
    })

    UrlField = make_input({
        label: 'UrlField',
        name: 'UrlField',
        placeHolder: '输入正确url'
    })

    TextField = CharField

    DateField = make_datepicker({
        label : 'DateField',
        name  : 'DateField',
        value : '',
        dateFormat : 'yyyy-mm-dd'
    })

    DateTimeField = make_datepicker({
        label : 'DateTimeField',
        name  : 'DateTimeField',
        value : '',
        dateFormat : 'yyyy-mm-dd'
    })

    TimeField = make_datepicker({
        label : 'TimeField',
        name  : 'TimeField',
        value : '',
        dateFormat : 'yyyy-mm-dd'
    })

    Select = function($parent,options){
        var configMap = {
                defaults : {
                    label : 'Select',
                    name : 'Select' + new Date().getTime(),
                    options : [],
                    placeHolder : '请选择...',
                    minimumResultsForSearch : Infinity,
                    multiple : '',
                    allowClear : true,
                    optons : options,
                    maximumSelectionLength : null,
                    tags : false,
                    ajax_url : null
                }
            },
            jqueryMap = {

            },
            setJqueryMap,setValue,getValue,setPlaceHolder,getPlaceHolder,setName,getName,
            disable,enable

        setJqueryMap = function(){
            var main_html = String() +
                    '<div class="form-group">'+
                        '<label class="control-label col-md-3">'+configMap.defaults.label + '</label>'+
                        '<div class="col-md-9">'+
                            '<select class="form-control select2 input-lg" '+
                            'multiple="' + configMap.defaults.multiple + '" ' +
                            'name="'+configMap.defaults.name + '" style="width:100%">'+
                            '</select>'+
                        '</div>'+
                    '</div>',
                $container = $(main_html),
                $select = $container.find("select")
                jqueryMap['$container'] = $container
                jqueryMap['$select'] = $select
                if(!configMap.defaults.ajax_url) {
                    jqueryMap['$select_instance'] = $select.select2({
                        placeholder: configMap.defaults.placeHolder,
                        minimumResultsForSearch: configMap.defaults.minimumResultsForSearch,
                        allowClear: configMap.defaults.allowClear,
                        data: configMap.defaults.options,
                        tags: configMap.defaults.tags
                    });
                } else {
                    jqueryMap['$select_instance'] = $select.select2({
                        placeholder: configMap.defaults.placeHolder,
                        minimumResultsForSearch: configMap.defaults.minimumResultsForSearch,
                        allowClear: configMap.defaults.allowClear,
                        tags: configMap.defaults.tags,
                        ajax : {
                            url : configMap.defaults.ajax_url,
                            dataType: 'json',
                            delay: 250,
                            data: function (params) {
                                return {
                                    q: params.term, // search term
                                    page: params.page
                                  };
                            },
                            processResults: function (data, params) {
                              // parse the results into the format expected by Select2
                              // since we are using custom formatting functions we do not need to
                              // alter the remote JSON data, except to indicate that infinite
                              // scrolling can be used

                                params.page = params.page || 1;

                                return {
                                    results: data.items,
                                    pagination: {
                                        more: (params.page * 30) < data.total_count
                                    }
                                };
                            },
                            cache: true
                        },
                        escapeMarkup: function (markup) { return markup; },
                        minimumInputLength: 1,
                        templateResult: formatRepo,
                        templateSelection: formatRepoSelection
                    });
                }
        }

        setValue = function(value){
            jqueryMap.$select_instance.val(value)
        }

        getValue = function(){
            return jqueryMap.$select_instance.value()
        }


        disable = function(){
            jqueryMap.$select.prop("disabled", false);
        }

        enable = function(){
            jqueryMap.$select.prop("disabled", true);
        }

        $.extend(configMap.defaults,options)
        setjqueryMap()
        $parent.append(jqueryMap.$container)

        return {
            setValue : setValue,
            getValue : getValue,
            disable : disable,
            enable : enable
        }


    }

    TreeSelect = function($parent,options){
        var configMap={
                defaults : {
                    label : 'TreeSelect',
                    name : 'TreeSelect'+new Date().getTime(),
                    data : [],
                    ajax_url : '',
                    model : 'model',
                    field : 'field',

                }
            },
            jqueryMap = {},
            setValue,getValue,disable,enable,setJqueryMap

        setJqueryMap = function(){
            var main_html = String() +
                    '<div class="form-group">'+
                        '<label class="col-md-3 control-label">'+configMap.defaults.label+'</label>'+
                        '<div class="col-md-9">'+
                            '<div class="input-group col-md-12">'+
                                '<input class="form-control" type="text" placeholder="" readonly>'+
                                '<span>'+
                                    '<button class="btn default date-reset" type="button"><i class="fa fa-times"></i></button>'+
                                '</span>'+
                                '<input type="hidden" name="'+configMap.defaults.name + '"/>'+
                            '</div>'+
                        '</div>'+
                        '<div class="tree_container"'+
                             'style="left:234px;display:none;position:absolute;border:1px solid grey;height:200px;width:500px;overflow:auto;background-color:white">'+
                            '<div class="tree-demo"></div>'+
                        '</div>'+
                    '</div>',
                $container = $(main_html),
                $input_name = $container.find("input .form-control"),
                $input_value = $container.find('input[type=hidden]'),
                $tree_container = $container.find('.tree_container'),
                $tree = $container.find(".tree-demo"),
                $button = $container.find('button'),
                $jstree
            jqueryMap['$container'] = $container
            jqueryMap['$input_name'] = $input_name
            jqueryMap['$input_value'] = $input_value
            jqueryMap['$tree_container'] = $tree_container
            jqueryMap['$tree'] = $tree
            jqueryMap['$button'] = $button

            $button.click(function (event) {
                    $tree.jstree("deselect_all")
                    $input_name.val("")
                    $input_value.val("")
            })

            if(configMap.defaults.ajax_url==='') {
                $jstree = $tree.jstree({
                    "core" : {
                    "themes" : {
                        "responsive": false
                    },
                    // so that create works
                    "check_callback" : true,
                    'data' : configMap.defaults.data
                },
                "types": {
                    "default": {
                        "icon": "fa fa-folder icon-state-warning icon-lg"
                    },
                    "file": {
                        "icon": "fa fa-file icon-state-warning icon-lg"
                    }
                },
                "state": {"key": "demo2"},
                "plugins": ["contextmenu", "dnd", "state", "types"]
                })
            } else {
                $jstree = $tree.jstree({
                    "core" : {
                        "themes" : {
                            "responsive": false
                        },
                        // so that create works
                        "check_callback" : true,
                        'data' : {
                            'url' : function (node) {
                                return configMap.defaults.ajax_url
                            },
                            'data' : function (node) {
                                return {
                                    'model' : configMap.defaults.model,
                                    'field' : configMap.defaults.field,
                                    'parent' : node.id,
                                    'level' : node.parents.length
                                };
                            }
                        }
                    },
                    "types": {
                        "default": {
                            "icon": "fa fa-folder icon-state-warning icon-lg"
                        },
                        "file": {
                            "icon": "fa fa-file icon-state-warning icon-lg"
                        }
                    },
                    "state": {"key": "demo2"},
                    "plugins": ["contextmenu", "dnd", "state", "types"]
                })
            }

            jqueryMap['$jstree'] = $jstree

            $jstree.on('select_node.jstree', function (e, data) {
                $input_name.val(data.node.text)
                $input_value.val(data.node.id)
                $tree_container.hide()
            })

            $tree_name.click(function(event){
                var
                    $group = $tree_input.parents('.form-group'),
                    tree_left = $input_name.offset().left - $group.offset().left

                $tree_container.toggle().css("zIndex", 20000)
                $tree_container.css({
                    left: tree_left + 'px',
                    top: $input_name.offset().top + 5 + 'px',
                    width: $input_name.css('width')
                })
                $tree.jstree()
                return false
            })
            $tree_container.click(function (event) {
                return false
            })

            $("body").click(function (event) {
                $tree_container.hide()
            })
        }

        setValue = function(value){

        }

        getValue = function(){

        }

        disable = function(){

        }

        enable = function(){

        }

        $.extend(configMap.defaults,options)
        setJqueryMap()
        $parent.append(jqueryMap.$container)

        return {
            setValue : setValue,
            getValue : getValue,
            disable  : disable,
            enable : enable
        }
    }

    return {
        CharField: CharField,
        TextField: TextField,
        IntegerField: IntegerField,
        NumbericField: NumericField,
        DateField: DateField,
        DateTimeField: DateTimeField,
        TimeField: TimeField,
        EmailField: EmailField,
        UrlField: UrlField,
        Select : Select,
        TreeSelect : TreeSelect
    }
}(jQuery))